<?php
/**
 * 哨兵每次只能选择一个主服务器
 */
// 配置 Redis 哨兵连接信息
$sentinels = [
    ['host' => '127.0.0.1', 'port' => 28001],
    ['host' => '127.0.0.1', 'port' => 28002],
    ['host' => '127.0.0.1', 'port' => 28003],
];

$masterName = 'master1';

// 创建 Redis Sentinel 实例并连接到 Redis 哨兵
foreach ($sentinels as $conf) {
    try{
        $sentinel = new RedisSentinel($conf);
        break;
    } catch (Exception $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
}
if (!$sentinel) {
    echo "sentinel list not avaliable";
}

// 获取监控的主节点的信息
$masterInfo = $sentinel->getMasterAddrByName($masterName);

// 连接到 Redis 主节点
$redis = new Redis();
$redis->pconnect($masterInfo[0], $masterInfo[1]);

// 执行 Redis 命令
$redis->set('key', 'value');
echo $redis->get('key');